package com.andnnl.fileanalysis;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * Created by chenss on 2022/6/9.
 */
public class ExcelListenerNew extends AnalysisEventListener<Map<Integer, String>> {
    private static final Logger logger = LoggerFactory.getLogger(ExcelListenerNew.class);
    private FileAnalysis analysis;
    private AnalysisListenerBase listener;
    private AnalysisParam param;
    private int rowCount = 0;
//    private int headRowCount = 0;

    public ExcelListenerNew(FileAnalysis analysis, AnalysisListenerBase listener, AnalysisParam param) {
        this.analysis = analysis;
        this.listener = listener;
        this.param = param;
    }

    /**
     * Returns the header as a map.Override the current method to receive header data.
     *
     * @param map
     * @param context
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> map, AnalysisContext context) {
        super.invokeHeadMap(map, context);
        if (null == map) return;
        Integer row = context.readRowHolder().getRowIndex()+1;//行号，从1开始
        List<String> list = IntStream.range(0, map.size()).mapToObj(k -> map.get(Integer.valueOf(k))).collect(Collectors.toList());
        //因为第1行默认是头,如需要删除头部
        param.getHeadRowCountAndAdd();//直接加1行
        logger.info("ignore head:" + map);
        analysis.handleHead(list,row, listener, param);

//            return;
    }

    /**
     * When analysis one row trigger invoke function.
     *
     * @param map     one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context analysis context
     */
    @Override
    public void invoke(Map<Integer, String> map, AnalysisContext context) {
        if (null == map) return;
        Integer row = context.readRowHolder().getRowIndex()+1;//行号，从1开始
        List<String> list = IntStream.range(0, map.size()).mapToObj(k -> map.get(Integer.valueOf(k))).collect(Collectors.toList());
        //easyExcel设置了删除头部行后,这里可不判断
        if (param.getDelHeadRows() > param.getHeadRowCount()) {
            param.getHeadRowCountAndAdd();
            logger.info("ignore head:" + map);
            analysis.handleHead(list,row, listener, param);
            return;
        }
        rowCount++;
        analysis.handleRow(list,row, listener, param);
        if (!(param.getMaxRow() == 0 || rowCount < param.getMaxRow())) {
            context.interrupt();//读够行数了就停止读取
        }
    }

    /**
     * if have something to do after all analysis
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        analysis.finish(listener, param);
        listener.finish();
    }
}
